package com.blb.edupayservice.listener;

import com.blb.common.entity.UserCourseOrder;
import com.blb.edupayservice.config.TimeoutOrderMQConfig;
import com.blb.edupayservice.feign.CourseServiceFeignClient;
import com.blb.edupayservice.feign.OrderServiceFeignClient;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;


/**
 * 超时消息监听器
 */
@Slf4j
@Component
public class TimeoutOrderListener {

    @Autowired
    private CourseServiceFeignClient courseServiceFeignClient;

    @Autowired
    private OrderServiceFeignClient orderServiceFeignClient;

    /**
     * 处理超时消息
     * @param tradeNo
     */
    @RabbitListener(queues = {TimeoutOrderMQConfig.DEADLETTER_ORDER_QUEUE})
    public void handleTimeoutOrder(String tradeNo, Channel channel, Message message){
        log.info("订单发生超时{}",tradeNo);
        try {
            //按订单号查询订单
            ResponseEntity<UserCourseOrder> orderEntity = orderServiceFeignClient.getOrderByTradeNo(tradeNo);
            UserCourseOrder order = orderEntity.getBody();
            //如果订单没有支付，修改订单状态
            if(order.getStatus() == 0) {
                //将订单状态改为取消2
                order.setStatus(2);
                orderServiceFeignClient.changeOrderStatus(order);
                //将课程活动的库存加1
                courseServiceFeignClient.addStock((int) order.getActivityId(), 1);
            }
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("超时订单处理完成{}",tradeNo);
        }catch (Exception ex){
            log.error("超时订单处理发生异常",ex);
        }
    }
}
